package com.ins.service.impl;

import com.ins.common.enums.ErrEnum;
import com.ins.common.exception.ServerException;
import com.ins.common.utils.SecureUser;
import com.ins.common.utils.ServerUtils;
import com.ins.mapper.AppResMapper;
import com.ins.model.entity.AppRes;
import com.ins.model.vo.UploadVO;
import com.ins.service.AppResService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.StrPool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;

/**
 * AppResServiceImpl
 *
 * @author aa
 * @version 1.0
 * @since 2024/8/23
 */
@Slf4j
@Service
public class AppResServiceImpl extends ServiceImpl<AppResMapper, AppRes> implements AppResService {

    @Value("${ins.domain}")
    private String domain;


    @Override
    public UploadVO upload(MultipartFile file) {
        Assert.isFalse(file.isEmpty(), () -> ServerException.spe("文件不存在"));
        String fileName = IdUtil.fastSimpleUUID();
        String extName = FileNameUtil.extName(file.getOriginalFilename());
        if (!ServerUtils.FILE_EXTS.contains(extName)) {
            throw new ServerException("文件格式不正确");
        }
        fileName = fileName + StrPool.DOT + extName;
        try {
            Path path = ServerUtils.UPLODA_PATH.resolve(fileName);
            file.transferTo(path.toFile());
            String visitPath = domain + "pic/" + fileName;
            AppRes appRes = new AppRes();
            appRes.setUrl(visitPath);
            appRes.setName(file.getOriginalFilename());
            appRes.setMd5(null);
            appRes.setSize(file.getSize());
            appRes.setType(extName);
            appRes.setTimeLine("0:0");
            appRes.setCreateBy(SecureUser.getUserName());
            appRes.setCreateTime(LocalDateTime.now());
            appRes.save();
            return new UploadVO(appRes.getId(), visitPath);
        } catch (IOException e) {
            log.error("文件上传失败：", e);
            throw new ServerException(ErrEnum.REQ_SERVER_ERR);
        }
    }
}
